import {
  constantRouterMap,
  constantRouterMapByTopJUI,
} from "@/config/router.config";
import { getListMenuByRoleId, getCurrentUserIndexPage } from "@/services/user";
import {
  BlankView,
  CommonLayout,
  TabsView,
  PageView,
  RouteView,
  PageLayout,
} from "@/layouts";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import Vue from "vue";
import { getCookie } from "@/utils/TopVUI.js";
import { GetUrlParam } from "@/utils/util.js";
import pick from "lodash/pick";
import { itemProps } from "ant-design-vue/es/vc-menu";
import { array } from "js-md5";
import router from "@/router";

import notification from "ant-design-vue/es/notification";
const MIS_ACCESS_TOKEN = localStorage.getItem("MIS_ACCESS_TOKEN");
let portalRoutersData = [];

import { mergeI18nFromRoutes } from "@/utils/i18n";
import { initI18n } from "@/utils/i18n";
const i18n = initI18n("zh_CN", "zh_CN");

/**
 * 过滤账户是否拥有某一个权限，并将菜单从加载列表移除
 *
 * @param permission
 * @param route
 * @returns {boolean}
 */
function hasPermission(permission, route) {
  if (route.meta && route.meta.permission) {
    let flag = false;
    for (let i = 0, len = permission.length; i < len; i++) {
      flag = route.meta.permission.includes(permission[i]);
      if (flag) {
        return true;
      }
    }
    return false;
  }
  return true;
}

/**
 * 单账户多角色时，使用该方法可过滤角色不存在的菜单
 *
 * @param roles
 * @param route
 * @returns {*}
 */
// eslint-disable-next-line
function hasRole(roles, route) {
  if (route.meta && route.meta.roles) {
    return route.meta.roles.includes(roles.id);
  } else {
    return true;
  }
}

// 匹配路由组件
function filterAsyncRouter(routerMap, roles) {
  const accessedRouters = routerMap.filter((route) => {
    // 门户首页数据处理
    if (
      process.env.VUE_APP_TYPE === "mis_vue" &&
      portalRoutersData &&
      portalRoutersData.length != 0
    ) {
      let index = portalRoutersData.findIndex(
        (item) => item.path === route.path
      );
      if (index !== -1 && route.id) {
        portalRoutersData[index].children[0].hidden = true;
        if (!route.children) route.children = [];
        route.children.push(portalRoutersData[index].children[0]);
      }
    }

    if (route.component) {
      // Layout组件特殊处理
      if (route.component === "TabsView") {
        route.component = TabsView;
      } else if (route.component === "CommonLayout") {
        route.component = CommonLayout;
      } else if (route.component === "PageLayout") {
        route.component = PageLayout;
      } else if (route.component === "BlankLayout") {
        route.component = BlankView;
      } else if (route.component === "PageView") {
        route.component = PageView;
      } else if (route.component === "RouteView") {
        route.component = RouteView;
      } else if (route.component === "BlankView") {
        route.component = BlankView;
      } else if (route.menuType === "urlInsidePage") {
        //链接内页 本系统的地址直接拼接${DataReportBaseUrl}  其他系统的直接写IP就行
        if (route.meta.urlInsidePageUrl.indexOf("{DataReportBaseUrl}") != -1) {
          route.meta.urlInsidePageUrl = route.meta.urlInsidePageUrl.replace(
            "{DataReportBaseUrl}",
            process.env.VUE_APP_API_BASE_URL
          );
        }
        route.meta.link = route.component;
        route.component = loadView("/system/urlInsidePage/index");
      } else {
        route.component = loadView(route.component);
      }
      if (route.meta) {
        route.meta.menuCode = route.menuCode ?? route.meta.title;
        route.meta.keepAlive = route.meta.keepAlive
          ? route.meta.keepAlive
          : route.keepAlive;
        route.meta.icon = route.meta.icon
          ? route.meta.icon
          : route.iconCls
          ? route.iconCls
          : "solution";
      }
      // 新窗口打开的路由
      if (route.menuType === "urlNewWindows") {
        if (route.menuUrl.indexOf("{BaseUrl}") != -1) {
          //
          let proCode = localStorage.getItem("CURRENT_PROJECT_CODE");
          let user_info = JSON.parse(localStorage.getItem("USER_INFO") ?? "{}");
          let currentProject = JSON.parse(
            localStorage.getItem("CURRENT_PROJECT") ?? "{}"
          );
          let { foreignUuid } = currentProject;
          route.path = appendParam(
            route.path,
            "proCode=" +
              proCode +
              "&userId=" +
              user_info.uuid +
              "&foreignUuid=" +
              foreignUuid
          );
          //
          route.path = route.path.replace(
            "{BaseUrl}",
            process.env.VUE_APP_API_REPORT_BASE_URL
          );
        }
        if (route.menuUrl.indexOf("{DataReportBaseUrl}") != -1) {
          route.path = route.path.replace(
            "{DataReportBaseUrl}",
            process.env.VUE_APP_API_BASE_URL
          );
        }
        if (route.menuUrl.indexOf("{token}") != -1) {
          route.path = route.path.replace("${token}", Vue.ls.get(ACCESS_TOKEN));
        }

        route.meta.target = "_blank";
        route.meta.link = route.path;
        delete route["component"];
      }
    }
    if (hasPermission(roles.permissionList, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route?.children ?? [], roles);
        if (route.name != 8) {
          delete route["redirect"];
        }
      } else {
        delete route["redirect"]; // 删除redirect重定向  防止堆用栈溢出
        delete route["children"]; // 删除没有数据的children  防止左侧菜单显示异常;
      }
      return true;
    }
    return false;
  });
  return accessedRouters;
}

//拼接路由参数
function appendParam(url, param) {
  const lastQuestionMarkIndex = url.lastIndexOf("?");
  if (lastQuestionMarkIndex === -1) {
    // 如果URL中没有问号,则使用?拼接参数
    return url.concat("?", param);
  } else if (lastQuestionMarkIndex === url.length - 1) {
    // 如果URL中最后一个字符是问号,则直接拼接参数
    return url.concat(param);
  } else {
    // 如果URL中最后一个问号不在末尾,则使用&拼接参数
    return url.concat("&", param);
  }
}

//单独处理路由path，将删除path后面的query参数
function dealRouteData(routerMap) {
  routerMap.forEach((route) => {
    let { children, path } = route;
    if (children && Array.isArray(children) && children.length > 0) {
      dealRouteData(children);
    } else {
      let newPath = path.split("?")[0];
      //判断是否是动态路由
      if (path.includes("/:")) {
        route.menuUrl = path.split("/:")[0];
        route.meta.autoRouter = true;
      } else {
        if (route.meta) {
          route.meta.autoRouter = false;
        } else {
          route.meta = {
            autoRouter: false,
          };
        }
      }
      route.path = newPath;
    }
  });
}

// 加载视图页面
export const loadView = (view) => {
  // 路由懒加载
  return (resolve) => require([`@/pages${view}`], resolve);
};
const permission = {
  state: {
    routers: !MIS_ACCESS_TOKEN ? constantRouterMapByTopJUI : constantRouterMap,
    addRouters: [],
    menuData: [],
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers;
      state.menuData = routers;
      state.menuData.push({ path: "*", redirect: "/404", hidden: true });
      state.routers = !MIS_ACCESS_TOKEN
        ? constantRouterMapByTopJUI.concat(routers)
        : constantRouterMap.concat(routers);
    },
  },
  actions: {
    GenerateRoutes({ commit, state }, data) {
      //获取动态路由数据
      return new Promise((resolve) => {
        let url = "";
        let ajaxData = {
          type: "dev",
        };
        // 判断是vue版还是topjui版本
        if (process.env.VUE_APP_TYPE === "mis_vue") {
          url = "/system/menu/getListMenuByRoleId";
        } else {
          url = "/system/menu/getAllVueMenuData";
          if (process.env.NODE_ENV === "production") {
            //判断取用那个菜单，主要针对于topjui版本的流程和表单
            ajaxData = {
              type: "production",
            };
          }
        }
        // vue版本菜单数据获取
        if (process.env.VUE_APP_TYPE === "mis_vue") {
          // 门户页面菜单获取
          getCurrentUserIndexPage().then((res) => {
            portalRoutersData = res;
            localStorage.setItem(
              "PORTAL_ROUTERS_DATA",
              JSON.stringify(res || [])
            );

            let urlParam = GetUrlParam(window.location.href);
            //oauth2要求携带
            let ajaxVueData = pick(urlParam, ["systemId"]);
            getListMenuByRoleId(url, ajaxVueData).then((res) => {
              let { statusCode, message } = res;
              if (statusCode != 200) {
                notification.error({
                  message: "系统提示",
                  description: message,
                  duration: 2,
                });
                localStorage.clear();
                commit("SET_TOKEN", "");
                commit("SET_ROLES", []);
                commit("SET_PHONE_NUMBER", "");
                return;
              }
              const { roles } = data;
              const array = [];
              const menuData = res.data?.children ?? [];
              array.push(menuData);
              const accessedRouters = filterAsyncRouter(menuData, roles);
              //如果配置 首页大屏  则在左侧菜单隐藏
              menuData.forEach((v) => {
                if (v.path === "/xtdp") {
                  v.hidden = true;
                }
              });
              //-------如果没有配置管理菜单，手动把系统门户挂载 2024-07-15
              //   let flag = accessedRouters.some((v) => v.path == "/system");
              //   let homeItem = portalRoutersData.find((v) => v.path == "/system");
              //   if (!flag && accessedRouters.length != 0) {
              //     homeItem.children[0].hidden = true;
              //     homeItem.children[0].menuCode = "system";
              //     homeItem.children[0].component = PageView;
              //     homeItem.children[0].children[0].component = PageView;
              //     accessedRouters[0].children.push(homeItem.children[0]);
              //   }

              commit("SET_ROUTERS", accessedRouters);
              dealRouteData(accessedRouters);

              //--------------------------------------------
              router.options.routes = accessedRouters;
              // 动态添加可访问路由表
              accessedRouters.forEach((v) => {
                router.addRoute(v);
              });
              //router.addRoutes(accessedRouters);
              // 提取路由国际化数据
              mergeI18nFromRoutes(i18n, accessedRouters);
              //   console.log(router.matcher, "router.matcher");
              //--------------------------------------------
              resolve(accessedRouters);
            });
          });
        } else {
          // topjui版本菜单获取
          getListMenuByRoleId(url, ajaxData).then((res) => {
            const { roles } = data;
            const array = [];
            const menuData = res.children;
            array.push(menuData);
            const accessedRouters = filterAsyncRouter(menuData, roles);
            commit("SET_ROUTERS", accessedRouters);
            resolve(accessedRouters);
          });
        }
      });
    },
  },
};

export default permission;
